<?php
declare (strict_types=1);

namespace app\mall\model;

/**
 * Class MallRegion
 * @package app\mall\model
 */
class MallRegion extends MallBase
{
    public function getChildCountAttr($value, $data)
    {
        return static::where('parent_id', $data['id'])->count();
    }

    public function getHasChildAttr($value, $data)
    {
        return !!$this->getChildCountAttr($value, $data);
    }

    public function setParentNamesAttr($value, $data)
    {
        if ($value) {
            $parentName = $value[count($value) - 1];
            if (!$parentName) {
                $this->set('parent_id', 0);
            } else {
                $parentId = MallRegion::where('name', $parentName)->field(['id'])->getData('id');
                $this->set('parent_id', $parentId ?: 0);
            }
        }
        return $value ? json_encode($value, JSON_UNESCAPED_UNICODE) : '[]';
    }

    public function getParentNamesAttr($value, $data)
    {
        return $value ? json_decode($value, true) : [];
    }

}
